package com.applications.codemash.database;

import com.applications.codemash.utility.exceptions.RecordNotFoundException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SessionStartDbAdapter extends SQLiteOpenHelper
{
	private static final String DB_NAME = "CodeMashSessions.db";
	private static final int DB_VERSION = 1;
	private static final String DB_TABLE_NAME = "session_list";
	private static final String DB_CREATE = "create table session_list (" +
			"sessionUri varchar(130) PRIMARY KEY," +
			"active int NOT NULL);";
	
	public SessionStartDbAdapter(Context context)
	{
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase adapter)
	{
		adapter.execSQL(DB_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase adapter, int oldVersion, int newVersion)
	{
		// TODO Auto-generated method stub
	}
	
	public void AddSession(String sessionUri, boolean activeState)
	{
		SQLiteDatabase db = getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("sessionUri", sessionUri);
		values.put("active", activeState);
		
		db.insert(DB_TABLE_NAME, null, values);
		db.close();
	}
	
	public void UpdateSession(String sessionUri, boolean activeState)
	{
		SQLiteDatabase db = getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put("active", activeState);
			
		db.update(DB_TABLE_NAME, values, "sessionUri = ?", new String[] { sessionUri });
		db.close();
	}
	
	public boolean GetActiveStateForSession(String sessionUri) throws RecordNotFoundException
	{
		SQLiteDatabase db = getReadableDatabase();
		
		try
		{
			Cursor c = db.query(DB_TABLE_NAME, null, "sessionUri = ?", new String[] { sessionUri }, null, null, null);
			boolean canAdvanceCursor = c.moveToNext();
			
			if (!canAdvanceCursor)
				throw new RecordNotFoundException("No Record for this URI");
			
			boolean result = c.getInt(1) == 1 ? true : false;
			c.close();
			
			return result;
		}
		catch (Exception ex)
		{
			throw new RecordNotFoundException(ex.getMessage());			
		}
		finally
		{
			db.close();
		}
	}
}